#include <stdio.h>
#include <string.h>
#include "stdint.h"

#include "usrList.h"

#include "usrError.h"

// 初始化队列
void initQueue(Queue *q) {
    q->front = 0;
    q->rear = 0;
}

// 入队操作
uint8_t enqueue(Queue *q, char *item, int length) {
    if ((q->rear + 1) % MAX_SIZE == q->front) {
        // printf("Queue is full.\n");
        return USR_LIST_FULL;
    }
    // strncpy(q->elements[q->rear].data, item, length);
    // q->elements[q->rear].data[length] = 0;
    for (size_t i = 0; i < length; i++)
    {
        q->elements[q->rear].data[i] = item[i];
    }
    q->elements[q->rear].length = length;
    q->rear = (q->rear + 1) % MAX_SIZE;
    return 0;
}

// 出队操作
QueueElement* dequeue(Queue *q) {
    QueueElement* empty_element = NULL;
    if (q->front == q->rear) {
        // printf("Queue is empty.\n");
        return empty_element;
    }
    empty_element = &(q->elements[q->front]);
    q->front = (q->front + 1) % MAX_SIZE;
    return empty_element;
}

// 查看队头元素
QueueElement peek(Queue *q) {
    QueueElement empty_element = {{0}, 0};
    if (q->front == q->rear) {
        printf("Queue is empty.\n");
        return empty_element;
    }
    return q->elements[q->front];
}

// 打印队列元素
void printQueue(Queue *q) {
    if (q->front == q->rear) {
        printf("Queue is empty.\n");
        return;
    }
    printf("Queue elements: \n");
    int i = q->front;
    while (i != q->rear) {
        printf("%.*s\n", q->elements[i].length, q->elements[i].data);
        i = (i + 1) % MAX_SIZE;
    }
}

void usrQueueInit(Queue* q)
{
    initQueue(q);
}

// int main() {
//     Queue q;
//     initQueue(&q);
    
//     enqueue(&q, "Element 1", strlen("Element 1"));
//     enqueue(&q, "Element 2", strlen("Element 2"));
//     enqueue(&q, "Element 3", strlen("Element 3"));
//     printQueue(&q);
    
//     QueueElement dequeued_element = dequeue(&q);
//     printf("Dequeued: %.*s\n", dequeued_element.length, dequeued_element.data);
//     dequeued_element = dequeue(&q);
//     printf("Dequeued: %.*s\n", dequeued_element.length, dequeued_element.data);
//     printQueue(&q);
    
//     enqueue(&q, "Element 4", strlen("Element 4"));
//     enqueue(&q, "Element 5", strlen("Element 5"));
//     printQueue(&q);
    
//     QueueElement front_element = peek(&q);
//     printf("Front element: %.*s\n", front_element.length, front_element.data);
    
//     return 0;
// }
